package smoker.server;

import java.io.IOException;
import java.net.*;

public class Server implements Runnable {
	public static final long serialVersionUID = 0;
	private ServerSocket serverSocket;
	private boolean isRunning;
	private IServerCenter iServerCenter;

	public Server(IServerCenter iServerCenter) {
		this.iServerCenter = iServerCenter;
	}

	public void run() {
		int port = iServerCenter.getServerPort();

		try {
			serverSocket = new ServerSocket(port);
		} catch (IOException e1) {
			e1.printStackTrace();
		}catch(Exception e) {
			e.printStackTrace();
		}

		int count = 0;
			try {
				while (isRunning) {
					Socket socket = serverSocket.accept();
					int key = count++;
					ConnectClientThread client = new ConnectClientThread(iServerCenter, socket, key);
					iServerCenter.addNewClientToMaps(socket, client, key);
					Thread.sleep(500);
				}
			} catch (IOException e) {
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	}

	public void startThread() {
		isRunning = true;
		new Thread(this).start();
	}

	public void stopThread() {
		isRunning = false;
		try {
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
